﻿<template>
  <section class="user">
    <div class="user_options-container">
      <div class="user_options-text">
        <div class="user_options-unregistered">
          <h2 class="user_unregistered-title">没有账号？</h2>
          <p class="user_unregistered-text">点击按钮注册成为会员.</p>
          <button class="user_unregistered-signup" id="signup-button" @click="showSignupForm">注册</button>
        </div>

        <div class="user_options-registered">
          <h2 class="user_registered-title">已有账号?</h2>
          <p class="user_registered-text">点击按钮会员登录.</p>
          <button class="user_registered-login" id="login-button" @click="showLoginForm">登录</button>

        </div>
      </div>

      <div class="user_options-forms" id="user_options-forms">
        <div class="user_forms-login" v-if="currentForm === 'login'">
          <h2 class="forms_title">登录</h2>
          <el-form :model="loginForm" :rules="rules" ref="loginForm" class="forms_form" @submit.prevent="handleLogin">
            <fieldset class="forms_fieldset">
              <div class="forms_field">
                <el-input v-model="loginForm.username" placeholder="名称" class="forms_field-input" required />

              </div>
              <div class="forms_field">
                <el-input v-model="loginForm.password" type="password" placeholder="密码" class="forms_field-input" required />
              </div>
              <div class="forms_field">
                <el-select v-model="loginForm.role" class="forms_field-input">
                  <el-option v-for="role in roles" :key="role.value" :value="role.label" :label="role.label"></el-option>
                </el-select>
              </div>
            </fieldset>
            <div class="forms_buttons">
              <button type="button" class="forms_buttons-forgot">忘记密码?</button>
              <el-button type="primary" native-type="submit" class="forms_buttons-action" @click="submitForm('loginForm')" :loading="submit.loading">登录</el-button>
            </div>
          </el-form>
        </div>
        <div class="user_forms-signup" v-if="currentForm === 'signup'">
          <h2 class="forms_title">注册</h2>
          <el-form :model="signupForm" :rules="rules" ref="signupForm" class="forms_form" @submit.prevent="handleSignup">
            <fieldset class="forms_fieldset">
              <div class="forms_field">
                <el-input v-model="signupForm.username" placeholder="名称" class="forms_field-input" required />
              </div>
              <div class="forms_field">
                <el-input v-model="signupForm.password" type="password" placeholder="密码" class="forms_field-input" required />
              </div>
              <div class="forms_field">
                <el-input v-model="signupForm.password2" type="password" placeholder="确认密码" class="forms_field-input" required />
              </div>
            </fieldset>
            <div class="forms_buttons">
              <el-button type="primary" native-type="submit" @click="zhuce('signupForm')" class="forms_buttons-action" :loading="submit.loading">注册</el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
import { Session } from '@/utils/storage';
import { formatDate, formatAxis } from '@/utils/formatTime';
import { PrevLoading } from '@/utils/loading.js';
import { login, register } from '@/api/login/index';

export default {
  name: 'login',
  data() {
    return {
      currentForm: 'login',
      loginForm: {
        name: '',
        password: '',
        role: '管理员'
      },
      signupForm: {
        name: '',
        password: '',
        password2: '',
        role: '用户'
      },
      roles: [
        { value: 'xuesheng', label: '学生' },
        { value: 'suguan', label: '老师' },
        { value: 'guanliyuan', label: '管理员' }
      ],
      submit: {
        loading: false,
      },
      rules: {
        username: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        password2: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    const signupButton = document.getElementById('signup-button');
    const loginButton = document.getElementById('login-button');
    const userForms = document.getElementById('user_options-forms');

    signupButton.addEventListener('click', () => {
      userForms.classList.remove('bounceRight');
      userForms.classList.add('bounceLeft');
    }, false);

    loginButton.addEventListener('click', () => {
      userForms.classList.remove('bounceLeft');
      userForms.classList.add('bounceRight');
    }, false);
  },
  methods: {
    // 登录按钮点击
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.submit.loading = true;
          // console.log(login())
          login(this.loginForm).then(res=> {
            let defaultRoles = [];
            let defaultAuthBtnList = [];
            // admin 页面权限标识，对应路由 meta.roles
            let guanliyuanRoles = ['guanliyuan'];
            let xueshengRoles = ['xuesheng'];
            let suguanRoles = ['suguan'];
            // admin 按钮权限标识
            let adminAuthBtnList = ['btn.add', 'btn.del', 'btn.edit', 'btn.link'];
            if (this.loginForm.role === '管理员') {defaultRoles = guanliyuanRoles;defaultAuthBtnList = adminAuthBtnList;}
            if (this.loginForm.role === '学生') {defaultRoles = xueshengRoles;defaultAuthBtnList = adminAuthBtnList;}
            if (this.loginForm.role === '老师') {defaultRoles = suguanRoles;defaultAuthBtnList = adminAuthBtnList;}



            let user = res.data.user;
            localStorage.setItem("username",this.loginForm.username);
            localStorage.setItem("cx", this.loginForm.role);
            user = {...user,time: new Date().getTime(),
              roles: defaultRoles,
              authBtnList: defaultAuthBtnList}
            Session.set('token', res.data.token);
            // 存储用户信息到浏览器缓存
            Session.set('userInfo',user);
            // 存储用户信息到vuex
            this.$store.dispatch('userInfos/setUserInfos',user);
            PrevLoading.start();
            this.submit.loading = false;
            this.$router.push('/');
            setTimeout(() => {
              this.$message.success(`${this.loginForm.role }，${this.$t('message.login.signInText')}`);
            }, 300);
          }).catch(msg =>{
            this.submit.loading = false;
            this.$message({
              type: 'error',
              message: msg
            })
          })
        }
      })
    },
    //注册按钮点击





    showSignupForm() {
      this.currentForm = 'signup';
    },
    showLoginForm() {
      this.currentForm = 'login';
    },
    zhuce(formName) {
      alert(111)
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(this.signupForm.password == this.signupForm.password2){
            register(this.signupForm).then(res=> {
              this.$message({
                type: 'success',
                message: '注册成功'
              })
              setTimeout(() => {
                this.$router.push('/login');
              }, 300);
            }).catch(msg =>{
              this.submit.loading = false;
              this.$message({
                type: 'error',
                message: msg
              })
            })
          }else {
            this.$message({
              type: 'error',
              message: '两次密码输入不一致'
            })
          }
        }
      })
    },
    handleLogin() {
      this.submit.loading = true;
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          login(this.loginForm)
              .then(res => {
                if (res.code === 200) {
                  const user = {
                    ...res.data.user,
                    time: new Date().getTime(),
                    roles: [this.loginForm.role], // Use selected role
                    authBtnList: [] // Default empty permissions
                  };

                  Session.set('token', res.data.token);
                  Session.set('userInfo', user);
                  this.$store.dispatch('userInfos/setUserInfos', user);
                  PrevLoading.start();
                  this.$router.push('/');
                  this.$message.success(`${formatAxis(new Date())}，登录成功`);
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch(error => {
                console.error(error);
                this.$message.error('登录失败');
              })
              .finally(() => {
                this.submit.loading = false;
              });
        } else {
          this.submit.loading = false;
          return false;
        }
      });
    },
    handleSignup() {
      this.submit.loading = true;
      this.$refs.signupForm.validate(valid => {
        if (valid) {
          if (this.signupForm.password !== this.signupForm.password2) {
            this.$message({
              type: 'error',
              message: '两次密码输入不一致'
            });
            this.submit.loading = false;
            return false;
          }
          const signupData = {
            ...this.signupForm,
            role: this.signupForm.role
          };
          register(signupData)
              .then(res => {
                if (res.code === 200) {
                  this.$message.success('注册成功，请登录');
                  this.currentForm = 'login';
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch(error => {
                console.error(error);
                this.$message.error('注册失败');
              })
              .finally(() => {
                this.submit.loading = false;
              });
        } else {
          this.submit.loading = false;
          return false;
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
@import "reset.min.css";
@import "style.css";
</style>
